package com.study.sbsummary.utils;

import com.truely.plog.serving.service.MessageService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static final String DEFAULT_PROFILE = "prod";

    private static ApplicationContext context;

    private static String[] activeProfiles;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static <T> T getBean(String beanName) {
        return (T) context.getBean(beanName);
    }

    public static String[] getActiveProfiles() {
        return context.getEnvironment().getActiveProfiles();
    }

    public static String activeProfile() {
        if (activeProfiles == null) {
            synchronized (MessageService.class) {
                if (activeProfiles == null) {
                    activeProfiles = SpringContextUtil.getActiveProfiles();
                    if (activeProfiles == null || activeProfiles.length == 0) {
                        activeProfiles = new String[]{DEFAULT_PROFILE};
                    }
                }
            }
        }
        return activeProfiles[0];
    }
}
